var http = require('http')
var fs = require('fs')
var url = require('url')

var msgs = [
]

var http_server = http.createServer();

http_server.on('request', function (req, res) {
	var cur_url = req.url
	console.log(cur_url)
	res.setHeader('content-type', 'text/html;charset=utf-8')
	if (cur_url == '/') {
		fs.readFile('./view/index.html', 'utf-8', function (err, data) {
			if (err) {
				console.log(err)
				return
			}
			var html = ''
			msgs.forEach(function (msg) {
				html += `<ul class="list-group">${msg.name}说：${msg.content}<span
				class="pull-right">${msg.create_at}</span></ul>`

			})
			var html = data.replace('123456', html)
			// console.log(html)
			res.end(html)
		})
	}
	else if (cur_url == '/add') {
		fs.readFile('./view/add.html', 'utf-8', function (err, data) {
			if (err) {
				console.log(err)
				return
			}
			res.end(data)
		})
	}
	else if (cur_url.indexOf('/doadd') === 0) {
		var param_obj = url.parse(req.url, true)
		// console.log(param_obj)
		var date = new Date()
		var date = date.getFullYear() + ' - ' + date.getMonth() + '-' + date.getDay() + '-' + date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds()
		var msg = {
			name: param_obj.query.name,
			content: param_obj.query.content,
			create_at: date
		}
		msgs.push(msg)
		// console.log(msgs)
		res.statusCode = 302
		res.setHeader('location', '/')
		res.end()
	}
	else if (cur_url == '/clr') {
		msgs = []
		res.statusCode = 302
		res.setHeader('location', '/')
		res.end()
	}
	else {
		fs.readFile('./view/404.html', 'utf-8', function (err, data) {
			if (err) {
				console.log(err)
				return
			}
			res.end(data)
		})
	}

})
http_server.listen(8080, function () {
	console.log("服务器启动成功,http://localhost:8080")
})